<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    title="固定参数配置"
    width="32%"
    showFooter
    :closable="false"
    @ok="handleSubmit"
  >
    <div class="group-list">
      <div class="group" v-for="(item, index) in groupData" :key="index">
        <div class="top">
          <h4>{{ item.tag }}</h4>
          <span class="price">单价：{{ item.price }}</span>
        </div>
        <div class="group-content">
          <ul :class="['time-list', (!item.times || item.times.length === 0) && 'empty']">
            <li class="time" v-for="(time, tIndex) in item.times" :key="tIndex">
              <div class="date"
                >时段{{ tIndex + 1 }}：{{ formatTime(time.startTime) }}-{{
                  formatTime(time.endTime)
                }}</div
              >
              <span class="link" type="link" @click="() => handleEditTime(time, index, tIndex)"
                >编辑</span
              >
              <a-divider type="vertical" />
              <a-popconfirm
                title="确认删除吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="() => handleDeleteTime(index, tIndex)"
              >
                <span class="link">删除</span>
              </a-popconfirm>
            </li>
          </ul>
          <div class="operate">
            <span class="link" @click="() => handleAddTime(index)">添加时段</span>
            <a-divider type="vertical" />
            <span class="link" @click="() => handleEditGroup(item, index)">编辑分段</span>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确认删除吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="() => handleDeleteGroup(index)"
            >
              <span class="link">删除分段</span>
            </a-popconfirm>
          </div>
        </div>
      </div>
    </div>
    <div class="center-box">
      <a-button @click="handleCreateGroup" type="primary" :icon="h(PlusOutlined)"
        >新增分段</a-button
      >
    </div>
    <ModalAddGroup @register="registerModal" @success="handleAddGroupSuccess" />
    <ModalAddTime @register="registerTimeModal" @success="handleAddTimeSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
  import { ref, reactive, h } from 'vue'
  import ModalAddGroup from './ModalAddGroup.vue'
  import ModalAddTime from './ModalAddTime.vue'
  import { useModal } from '@/components/Modal'
  import { createPrompt } from '@/components/Prompt'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { buildUUID } from '@/utils/uuid'
  import message from '@/views/form-design/utils/message'
  import dayjs from 'dayjs'
  import { addSettingPrice, getSettingPriceDetail } from '@/api/sys/energyUnitPrice'

  defineOptions({ name: 'DrawerSetting' })

  const isUpdate = ref(false)
  const rowId = ref()
  let groupData = ref([])
  const energyPriceId = ref()
  const [registerModal, { openModal: openModalGroup }] = useModal()
  const [registerTimeModal, { openModal: openModalTime }] = useModal()

  const [registerDrawer, { setDrawerProps, closeDrawer, changeLoading }] = useDrawerInner(
    async (data) => {
      const id = data.record.id
      energyPriceId.value = id
      changeLoading(true)
      const res = await getSettingPriceDetail({ energyPriceId: id })
      changeLoading(false)
      groupData.value = res
    },
  )

  const formatTime = (time) => {
    const [hours, minutes] = time.split(':').map(Number)
    const date = dayjs().hour(hours).minute(minutes)

    return dayjs(date).format('HH:mm')
  }

  const handleCreateGroup = () => {
    openModalGroup(true, { isUpdate: false, groupData: groupData.value })
  }

  const handleEditGroup = (data, index) => {
    openModalGroup(true, {
      isUpdate: true,
      data,
      index,
      groupData: groupData.value,
    })
  }
  // 删除分段
  const handleDeleteGroup = (index) => {
    groupData.value.splice(index, 1)
    message.success('删除成功')
  }
  const handleAddTime = (groupIndex) => {
    // 新增的项的index为当前数组长度+ 1
    openModalTime(true, {
      isUpdate: false,
      groupIndex,
      timeIndex: groupData.value[groupIndex].times.length,
    })
  }

  // 编辑时段
  const handleEditTime = (time, groupIndex, timeIndex) => {
    openModalTime(true, { isUpdate: true, data: time, groupIndex, timeIndex })
  }

  // 删除时段
  const handleDeleteTime = (groupIndex, timeIndex) => {
    groupData.value[groupIndex].times.splice(timeIndex, 1)
    message.success('删除成功')
  }

  // 添加分段
  const handleAddGroupSuccess = ({ isUpdate, data: { values, groupIndex } }) => {
    if (isUpdate) {
      Object.assign(groupData.value[groupIndex], values)
    } else {
      groupData.value.push({ ...values, energyPriceId: energyPriceId.value, times: [] })
    }
  }
  const handleAddTimeSuccess = ({ isUpdate, values, groupIndex, timeIndex }) => {
    if (isUpdate) {
      groupData.value[groupIndex].times.splice(timeIndex, 1, values)
    } else {
      groupData.value[groupIndex].times.push(values)
    }
  }

  const handleSubmit = () => {
    const data = groupData.value.map((item) => ({
      ...item,
      times: item.times.map((time, index) => ({
        ...time,
        name: `时段${index + 1}`,
      })),
    }))
    addSettingPrice(data).then((res) => {
      message.success('配置成功')
      closeDrawer()
    })
  }
</script>

<style lang="scss" scoped>
  .group-list {
    .link {
      color: #0067cc;
      font-size: 12px;
      cursor: pointer;
    }

    .top {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      h4 {
        position: relative;
        flex: 1;
        margin: 0;
        color: #181818;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: -16px;
          width: 4px;
          height: 12px;
          transform: translateY(-50%);
          background: #939393;
        }
      }
    }

    .group-content {
      .time-list {
        border: 1px solid #ccd4db;

        &.empty {
          height: 24px;
          border: 1px dashed rgb(204 212 219 / 100%);
        }

        .time {
          display: flex;
          align-items: center;
          height: 24px;
          padding: 0 12px;
          background: rgb(0 103 204 / 10%);
          color: #666;
          font-size: 12px;

          &:not(:last-child) {
            border-bottom: 1px solid #ccd4db;
          }

          .date {
            flex: 1;
          }
        }
      }

      .operate {
        margin: 8px 0;
      }
    }
  }

  .center-box {
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px dashed #ccd4db;
    text-align: center;
  }
</style>
